package com.zj003.module.sys.service.impl;

import com.zj003.common.constant.MenuType;
import com.zj003.common.domain.entity.SysMenu;
import com.zj003.common.util.SecurityUtils;
import com.zj003.module.sys.mapper.SysMenuMapper;
import com.zj003.module.sys.service.SysMenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author RedName
 * @description 针对表【sys_menu(菜单权限表)】的数据库操作Service实现
 * @createDate 2022-05-01 03:30:07
 */


@Slf4j
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl implements SysMenuService {
    private final SysMenuMapper menuMapper;

    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long userId) {

        if (SecurityUtils.isAdmin(userId)) {
            return buildTree(menuMapper.selectMenuTreeAll());
        }

        return buildTree(menuMapper.selectMenuTreeByUserId(userId));
    }


    private List<SysMenu> buildTree(List<SysMenu> menus) {
        Stream<SysMenu> menuStream = menus.stream().filter(menu -> menu.getMenuType().equals(MenuType.CATALOGUE)).peek(menu -> menu.setChildren(getChildren(menu, menus))).sorted(Comparator.comparingInt(menu -> (menu.getOrderNum() == null ? 0 : menu.getOrderNum())));
        return menuStream.collect(Collectors.toList());
    }

    private List<SysMenu> getChildren(SysMenu root, List<SysMenu> list) {
        return list.stream().filter(menu -> root.getMenuId().longValue() == menu.getParentId().longValue()).collect(Collectors.toList());

    }
}
